package com.lw.lwte.common.util;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.imageio.ImageIO;

public class ScreenshotTool {

    private Robot robot;

    public ScreenshotTool() throws AWTException {
        // 创建Robot实例
        robot = new Robot();
    }

    /**
     * 捕获整个屏幕的截图
     *
     * @param filePath 截图保存的路径和文件名
     * @throws IOException 如果保存截图时发生错误
     */
    public void captureFullScreen(String filePath) throws IOException {

        pathCheck(filePath);

        // 获取屏幕的大小
        Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        // 捕获屏幕的内容
        BufferedImage bufferedImage = robot.createScreenCapture(screenRect);
        // 将截图保存为PNG文件
        ImageIO.write(bufferedImage, "PNG", new File(filePath));
    }

    /**
     * 捕获指定区域的截图
     *
     * @param filePath  截图保存的路径和文件名
     * @param rectangle 要截图的区域
     * @throws IOException 如果保存截图时发生错误
     */
    public void captureArea(String filePath, Rectangle rectangle) throws IOException {
        pathCheck(filePath);
        // 捕获指定区域的内容
        BufferedImage bufferedImage = robot.createScreenCapture(rectangle);
        // 将截图保存为PNG文件
        ImageIO.write(bufferedImage, "PNG", new File(filePath));
    }

    public void pathCheck(String path) {
        File file = new File(path);
        // 确保父目录存在
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }
    }
}